package br.com.rsrpp.application.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import br.com.rsrpp.domain.model.Usuario;
import br.com.rsrpp.domain.service.UserService;

import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.types.User;

@Controller
public class LoginController {
	
	@Autowired
	private UserService userService;
	
    @RequestMapping(value = "/login")
    public String Login(HttpSession session, 
    					HttpServletRequest request, 
    					HttpServletResponse response) throws Exception {
    	
    	Usuario user = null;
    	String url = "redirect:/" + session.getAttribute("url");
    	
    	String token = request.getParameter("token");
    	
    	FacebookClient facebookClient = new DefaultFacebookClient(token);
    	
    	try {
    		User facebookUser = facebookClient.fetchObject("me", User.class);
    		
            List<Usuario> listUser = userService.buscarUserByEmail(facebookUser.getEmail());
            
            if(listUser.size() == 0) {	
            	
            	String FBemail = facebookUser.getEmail();
            	String FBname = facebookUser.getName();
            	String FBpic = facebookUser.getUsername();
            	FBpic = "https://graph.facebook.com/" + FBpic + "/picture";
            	         	
            	session.setAttribute("FBemail", FBemail);
            	session.setAttribute("FBname", FBname);
            	session.setAttribute("FBpic", FBpic);
            	
            	return "redirect:/carregarCadastrarUsuario.html";
            	
            } else {

            	String FBpic = facebookUser.getUsername();
            	FBpic = "https://graph.facebook.com/" + FBpic + "/picture";
            	
            	user = listUser.get(0);
                session.setAttribute("user", user);
            	session.setAttribute("logado", true);
            	session.setAttribute("FBpic", FBpic);
            	
    			if (session.getAttribute("url") != null)
    				return url;
    			else
    				return "redirect:/carregarMeusPS.html";
            }
		} catch (Exception e) {
			return "redirect:/carregarLogin.html?fbexception";
		}
    }
}
